package com.put.mybills.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.put.mybills.BaseDriveActivity;
import com.put.mybills.R;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.adapter.NavDrawerListAdapter;
import com.put.mybills.model.NavDrawerItem;
import com.put.mybills.service.NotyficationService;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**	
 * 
 * @author Piotr Baranski
 * MainActivity - this is main activity to startup app.
 * Here is setting importatnt parameters like drawing list items. 
 */

public class MainActivity extends BaseDriveActivity {
	
	private static final String TAG = "MainActivity";
	
	public static GlobalParams globalParams;
	
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;    
    // nav drawer title
    private CharSequence mTitle;
    
    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;   
    
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;
    
    private boolean isMyServiceRunning() {
	    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (NotyficationService.class.getName().equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
    
    private void sheduleService() {
    	Log.d(TAG, "Shedule service");
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    	Calendar calendar = Calendar.getInstance();	    
	    calendar.set(Calendar.HOUR_OF_DAY, 15);
	    calendar.set(Calendar.MINUTE, 0);
	    calendar.set(Calendar.SECOND, 0);
	    PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, NotyficationService.class),PendingIntent.FLAG_UPDATE_CURRENT);
	    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
	    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pi);
	    sharedPreferences.edit().putString("firstTime", "y").commit();    	
    }

	@Override
    protected void onCreate(Bundle savedInstanceState) {    	
        super.onCreate(savedInstanceState);    
     
        globalParams = new GlobalParams(this);
    	
        //set language
        Locale locale = getResources().getConfiguration().locale;
    	Locale.setDefault(locale);
    	Configuration config = new Configuration();
    	config.locale = locale;
    	getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
    	setContentView(R.layout.activity_main); 
    	
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    	if(!sharedPreferences.getString("firstTime", "").equals("y")){    		
    		Log.d(TAG, "First Time");    		
    		sheduleService();
    	}
    	else {    		
    		if (!isMyServiceRunning())
    			sheduleService();		
    	}

    	getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    
        int i = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);        
        if (i == ConnectionResult.SERVICE_DISABLED) {        	
        	Log.d("Google Play" , "Not installed" + i);
        }
        else if (i == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {        	
        	Log.d("Google Play" , "Updated required" + i);
        }
        else if ( i == ConnectionResult.SUCCESS) {      	
        	Log.d("Google Play" , "Everything good " +  GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_PACKAGE);
        }

        mTitle = mDrawerTitle = this.getResources().getString(R.string.app_name);
        
        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);        
        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
       
        // nav drawer icons from resources
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);             
        
        navDrawerItems = new ArrayList<NavDrawerItem>();  
        //navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),true, "2")); 
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));       
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));       
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));      
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));         
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

    	// Recycle the typed array
        navMenuIcons.recycle();
        
        adapter = new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);
        mDrawerList.setAdapter(adapter);
        
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {        	
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        
        mDrawerLayout.setDrawerListener(mDrawerToggle);
       

        if (savedInstanceState == null) {
        	displayView(0);
        }
        
        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
      
        
	
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);    	
        return true;
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	 // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        //menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         
    	// toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
	        case R.id.action_settings:
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }   
    
    private class SlideMenuClickListener implements  OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		    // display view for selected nav drawer item
		    displayView(position);
		}
    }
    
   
		
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:        
        	 fragment = new MyFactureFragment();
        	 break;
        case 2:
        	fragment = NewBillFragment.newInstance();
            break;
        case 3:        	
        	fragment = CloudFragment.newInstance();
            break;
        case 4:
        	fragment = new ChartsFragment();
            break;
        case 5:  
        	fragment = SettingsFragment.newInstance();
            break;
 
        default:
            break;
        }
 
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
            fragmentManager.invalidateOptionsMenu();
            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {		            
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
    
    @Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}
    
    @Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	   super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
		
    
    
}